# -*- coding: utf-8 -*-
# @Time: 2025/5/23 16:58
# @Author: wzd
# @Email: 2146333089@qq.com
# @File: jwt_utils.py
import jwt
from datetime import datetime, timedelta
from django.conf import settings
from django.http import JsonResponse

SECRET_KEY = settings.SECRET_KEY
JWT_EXPIRATION_HOURS = getattr(settings, 'JWT_EXPIRATION_HOURS', 24)


def generate_jwt_token(user_id, user_type, school_id=None):
    """生成JWT Token，包含用户ID、类型和学校信息"""
    payload = {
        'user_id': user_id,
        'user_type': user_type,
        'school_id': school_id,  # 可能为None
        'exp': datetime.utcnow() + timedelta(hours=JWT_EXPIRATION_HOURS),
        'iat': datetime.utcnow()
    }
    token = jwt.encode(payload, SECRET_KEY, algorithm='HS256')
    return token


def decode_jwt_token(token):
    """验证并解析JWT Token"""
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])
        return payload
    except jwt.ExpiredSignatureError:
        return None
    except jwt.InvalidTokenError:
        return None


def jwt_required(view_func):
    """JWT认证装饰器"""

    def _wrapped_view(request, *args, **kwargs):
        token = request.headers.get('Authorization')

        if not token:
            return JsonResponse({'code': 401, 'message': '缺少认证Token'}, status=401)

        if token.startswith('Bearer '):
            token = token[7:]

        payload = decode_jwt_token(token)
        if not payload:
            return JsonResponse({'code': 401, 'message': '无效或过期的Token'}, status=401)

        request.user_id = payload['user_id']
        request.user_type = payload['user_type']
        request.school_id = payload.get('school_id')  # 学生和教师会有值，管理员可能为None

        return view_func(request, *args, **kwargs)

    return _wrapped_view